package cc.geeksearch.ble

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import cc.geeksearch.ble.bean.DeviceBean
import kotlinx.coroutines.flow.MutableStateFlow

class MainActivity : ComponentActivity() {
    private val TAG = "MainActivity"
    @RequiresApi(Build.VERSION_CODES.S)
    val REQUIRED_PERMISSIONS_GE_S = arrayOf(

        android.Manifest.permission.ACCESS_FINE_LOCATION,
        android.Manifest.permission.BLUETOOTH_SCAN, android.Manifest.permission.BLUETOOTH_CONNECT
    )
    val REQUIRED_PERMISSIONS_LT_S = arrayOf(
        android.Manifest.permission.BLUETOOTH,
        android.Manifest.permission.ACCESS_FINE_LOCATION
    )

    private val PERMISSION_REQUEST_CODE = 1
    private val deviceList = MutableStateFlow(listOf<DeviceBean>())

    // 已拒绝权限
    private var deniedPermissions by mutableStateOf(false)

    @SuppressLint("StateFlowValueCalledInComposition")
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            val devices by deviceList.collectAsState()
            Scaffold(modifier = Modifier.fillMaxSize(), topBar = {
                TopAppBar(
                    title = { Text(text = stringResource(R.string.app_name)) },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer,
                        titleContentColor = MaterialTheme.colorScheme.primary,
                    ),
                    actions = {
                        // 添加一个加号图标按钮
                        IconButton(onClick = {
                            // 点击时跳转到 ScanActivity
                            val intent = Intent(this@MainActivity, ScanActivity::class.java)
                            startActivity(intent)
                        }) {
                            Icon(
                                imageVector = Icons.Default.Add,
                                contentDescription = stringResource(R.string.add_device)
                            )
                        }
                    },
                )
            }) { innerPadding ->
                if (deniedPermissions) {
                    ShowDisabledPermissionDialog(Modifier.padding(innerPadding))
                }
                if (devices.isNotEmpty()) {
                    DeviceList(devices = devices, Modifier.padding(innerPadding))
                } else {
                    AddDeviceButton(
                        onClick = {
                            addDevice()
                        },
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }

        LiveDataBus.devicesLiveData.observe(this) {
            WalleLog.d(TAG, "devicesLiveData: $it")
            val list = mutableListOf<DeviceBean>()
            list.addAll(it)
            deviceList.value = list
        }
    }

    private fun addDevice() {
        if (!hasPermissions()) {
            requestPermissions()
            return
        }
        val intent = Intent(this, ScanActivity::class.java)
        startActivity(intent)
    }

    private fun hasPermissions(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            for (permission in REQUIRED_PERMISSIONS_GE_S) {
                if (ContextCompat.checkSelfPermission(
                        this,
                        permission
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    return false
                }
            }
        } else {
            for (permission in REQUIRED_PERMISSIONS_LT_S) {
                if (ContextCompat.checkSelfPermission(
                        this,
                        permission
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    return false
                }
            }
        }
        return true
    }

    private fun requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            ActivityCompat.requestPermissions(
                this,
                REQUIRED_PERMISSIONS_GE_S,
                PERMISSION_REQUEST_CODE
            )
        } else {
            ActivityCompat.requestPermissions(
                this,
                REQUIRED_PERMISSIONS_LT_S,
                PERMISSION_REQUEST_CODE
            )
        }
    }

    override fun onResume() {
        super.onResume()
        Walle.getInstance(this).getDevices()
    }


    @Composable
    fun AddDeviceButton(onClick: () -> Unit, modifier: Modifier = Modifier) {
        Box(modifier = modifier.fillMaxSize()) {
            Button(
                onClick = { onClick() },
                modifier = Modifier.align(Alignment.Center)
            ) {
                Icon(imageVector = Icons.Default.Add, contentDescription = null)
                Text(text = stringResource(R.string.add_device))
            }
        }
    }


    @Composable
    fun DeviceList(devices: List<DeviceBean>, modifier: Modifier = Modifier) {
        LazyColumn(modifier = modifier) {
            itemsIndexed(devices) { index, deviceItem ->
                Column(
                    modifier = Modifier
                        .padding(10.dp)
                        .clickable {
                            val intent = Intent(this@MainActivity, DeviceActivity::class.java)
                            intent.putExtra("address", deviceItem.address)
                            intent.putExtra("name", deviceItem.name)
                            intent.putExtra("status", deviceItem.status)
                            intent.putExtra("remark", deviceItem.remark)
                            startActivity(intent)
                        }) {
                    val connectStatusName = when (deviceItem.status) {
                        DeviceStatus.NOT_CONNECTED -> stringResource(R.string.status_not_connected)
                        DeviceStatus.CONNECTED -> stringResource(R.string.status_connected)
                        DeviceStatus.CONNECTING -> stringResource(R.string.status_connecting)
                        DeviceStatus.PREPARED -> stringResource(R.string.status_prepared)
                        DeviceStatus.DISCONNECTED -> stringResource(R.string.status_disconnected)
                        DeviceStatus.CONNECT_FAILED -> stringResource(R.string.status_failed)
                        else -> ""
                    }
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 5.dp)
                    ) {
                        Text(
                            text = deviceItem.name,
                            fontSize = 18.sp,
                            modifier = Modifier.align(Alignment.TopStart)
                        )

                        Text(
                            text = deviceItem.remark,
                            fontSize = 18.sp,
                            modifier = Modifier.align(Alignment.TopEnd)
                        )
                    }

                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 5.dp)
                    ) {
                        Text(
                            text = deviceItem.address,
                            fontSize = 12.sp,
                            modifier = Modifier.align(Alignment.TopStart)
                        )
                        Text(
                            text = connectStatusName,
                            fontSize = 12.sp,
                            modifier = Modifier.align(Alignment.TopEnd)
                        )
                    }

                }
                // 在每个设备项之后添加分隔线，除了最后一个设备项
                if (index < devices.size - 1) {
                    androidx.compose.material3.HorizontalDivider()
                }
            }

        }
    }

    @Composable
    fun ShowDisabledPermissionDialog(modifier: Modifier = Modifier) {
        WalleLog.w("MainActivity", "showlog")
        Box(
            modifier = modifier
                .fillMaxWidth()
                .background(MaterialTheme.colorScheme.primary)
                .padding(10.dp)
        ) {
            Text(
                text = "未授权相关权限",
                color = MaterialTheme.colorScheme.background,
                modifier = Modifier.align(Alignment.TopCenter),
            )
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String?>,
        grantResults: IntArray,
        deviceId: Int
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults, deviceId)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            var allPermissionsGranted = true
            for (result in grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false
                    break
                }
            }
            if (allPermissionsGranted) {
                // 所有权限都已授予，执行添加设备的操作
                addDevice()
            } else {
                // 某些权限未授予，处理权限拒绝的情况
                // 这里可以显示一个提示信息给用户

                WalleLog.w("MainActivity", "未授权蓝牙权限 $deniedPermissions")
                runOnUiThread {
                    deniedPermissions = true
                }
            }
        }
    }

}






